package com.mini.auth.service;

import com.mini.admin.api.entity.SysUser;
import com.mini.admin.api.openfeign.AdminUserOpen;
import com.mini.auth.details.OAuthUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 根据用户名获取用户
 * @author Zhou Feng
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminUserOpen userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (username==null||"".equals(username.trim())){
            throw new UsernameNotFoundException("用户不存在");
        }
        SysUser user = userService.getUserByUsername(username).getData();
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        OAuthUserDetails oauthUserDetails = new OAuthUserDetails(user);
        if (!oauthUserDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        }
        return oauthUserDetails;
    }

    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        if (mobile==null||"".equals(mobile.trim())){
            throw new UsernameNotFoundException("用户不存在");
        }
        SysUser user = userService.getUserByMobile(mobile).getData();
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        OAuthUserDetails oauthUserDetails = new OAuthUserDetails(user);
        if (!oauthUserDetails.isEnabled()) {
            throw new DisabledException("该账户已被禁用!");
        }
        return oauthUserDetails;
    }
}
